/**
 * 	StatActivity.java：用來呈現排序後的紀錄或用關鍵字搜尋
 * 	
 * 	工作原理：
 * 		排序
 * 		-- 會先讀取app全域的hymns資料
 * 		-- 點spinner的項目選排序方法
 * 		-- 在下面的gridView就會依據排序方法把紀錄列出來
 * 		搜尋
 * 		-- 在搜尋欄填入關鍵字，會去搜尋各欄的關鍵字，再把它呈現出來
 */

package com.cwhuang.g7_tool_myhymns;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;

public class StatActivity extends Activity{
	private static final int STAT_EDIT = 1;
	AppHymns myHymns;
	private Spinner statSpinner;
	private String[] statItems;
	private GridView hymnsGrid;
	private ArrayAdapter<String> statAdapter;
	private SimpleAdapter saGrid;
	private Context context;
	private boolean showAll;
		
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stat);
        context = this;			//因為沒加這一行讓我debug了一個半小時QQ
        myHymns = (AppHymns)getApplicationContext();
        
        getViews();
        setClickListeners();
        
    }//end onCreate
    
    private void setClickListeners() {
    	//點GridView，能到DetailAdd那編輯
        hymnsGrid.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				//要處理的資料其實只有title...因為其他都不是唯一的名稱= =
				LinearLayout linearLayout = (LinearLayout)arg1;
				TextView textViewIndex= (TextView)linearLayout.getChildAt(0);
				String index= textViewIndex.getText().toString();
				TextView textViewTitle = (TextView)linearLayout.getChildAt(1);
				String title = textViewTitle.getText().toString();
				
				//在這裡要把丟的資料處理好；在detailAdd.java要有bundle去接資料
				Intent intent = new Intent(context, DetailAddActivity.class);
				Bundle bundle = new Bundle();
				bundle.putString("col_index", index);
				bundle.putString("col_title", title);
				intent.putExtras(bundle);
				
				//到DetailAdd後回來，要把資料重新整理，所以用forResult
				startActivityForResult(intent, STAT_EDIT);
			}
		});	//end hymnsGrid.setOnItemClickListener
        
        //點spinner的項目，可以依照所選項目條件排序
        statSpinner.setOnItemSelectedListener( 
    		new OnItemSelectedListener() {
				public void onItemSelected(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					int choice = arg0.getSelectedItemPosition();
					showAll = true;
					
					//重要！！最好不要讓hymns的順序被打亂，若沒有打亂，就可以直接用serial找到詩
					//TODO 所以先用一個方法複製by data，把hymns丟給copyHymns再排序 
					
					List list = myHymns.hymns;		//轉換成List用Collections的方法排序
					
					switch (choice) {
					case 0:
						//用serial
						Collections.sort(list, new StatActivity.SerialCompare() );
						showGrid(context, showAll);
						break;
					case 1:
						//用index排
						Collections.sort(list, new StatActivity.IndexCompare() );
						showGrid(context, showAll=false);
						break;
					case 2:
						//用rating排
				        Collections.sort(list, new StatActivity.RatingCompare() );
				        showGrid(context, showAll=false);
						break;
					case 3:
						//用唱的次數排
						Collections.sort(list, new StatActivity.TimesCompare() );
						showGrid(context, showAll=false);
						break;
					case 4:
						//用熟悉度排
						Collections.sort(list, new StatActivity.FamiliarityCompare() );
						showGrid(context, showAll=false);
						break;
					default:
						break;
					}
					//選擇完後，要再更新hymnsGrid的資料
					//似乎可以用DataSetObserver更新，可是看不太懂怎麼用
				}

				public void onNothingSelected(AdapterView<?> arg0) {}
		});//end statSpinner.setOnItemSelectedListener
	}	//end setClickListeners()

	private void getViews() {
    	//用spinner列出排序的方法
        statSpinner = (Spinner)findViewById(R.id.stat_spinner);
        statItems = getResources().getStringArray(R.array.stat);
        statAdapter = new ArrayAdapter<String>(
        		this,
        		android.R.layout.test_list_item, 
        		statItems);
        	//setDropDownViewRecource可以避免setAdapter時，spinner變得又肥又醜
        statAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        statSpinner.setAdapter(statAdapter);
        statSpinner.setSelection(2);
    	
      //用GridView列出資料
        hymnsGrid = (GridView)findViewById(R.id.stat_gridview);
        showAll=false;
        showGrid(context, showAll);
	}	//end getViews()

	//處理別的活動傳回來的東西。如果編輯了statActivity裡面的詩歌項目
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	super.onActivityResult(requestCode, resultCode, data);
    		//管你那麼多，反正就是給我更新就對了
			showGrid(context, showAll);
    }
    
    //為了無聊的gridView任性的一定要用map的list，就這樣送給它吧    
    public List<? extends Map<String, ?>> turnHymnsToListOfMap(boolean showAll){
    	//因為排序時要純資料，所以這些附加的資訊要在排序後加，
    	//又因為如果把這些資料加進去後，之後的hymns會不能排序，所以用tempHymns暫存
    	//這是一個deep clone(我不會用clone的方法...orz)
    	ArrayList<Map<String, Object>> tempHymns = new ArrayList<Map<String, Object>>();

    	for(Map<String, Object> map : myHymns.hymns){
    		//如果不要求要全部show出，那麼若紀錄評分或熟悉度不為零的map，就要加入tempHymns
    		//相反的，要排除掉那些紀錄評分或熟悉度都為零的map
    		if (showAll == false) {
    			if(map.get("col_rating").toString().equals("0") && 
    			   map.get("col_times").toString().equals("0") && 
    			   map.get("col_familiarity").toString().equals(
    					   getResources().getString(R.string.unknown_familiarity) ) 
    			   ){continue;}
			}
    			
    		HashMap<String, Object> tempMap = new HashMap<String, Object>();
    		
    		tempMap.put("col_index", map.get("col_index") );
    		tempMap.put("col_title", map.get("col_title") );
    		if(map.get("col_rating")!= null){
    			tempMap.put("col_rating", map.get("col_rating").toString() + "星等");
    		}else {tempMap.put("col_rating", "無星等");}
    		
    		if(map.get("col_times")!=null){
    			tempMap.put("col_times", map.get("col_times").toString() + "次");
    		}else{tempMap.put("col_times", "0次");}
    		
    		if(map.get("col_familiarity")!=null){
    			tempMap.put("col_familiarity", map.get("col_familiarity").toString() );
    		}else {
    			tempMap.put("col_familiarity", getResources().getString(R.string.unknown_familiarity));
    		}
			
			tempHymns.add(tempMap);
    	}
    	return tempHymns;
    }//end turnHymnsToListOfMap
    
    //為了減少重複的程式碼：因為gridview不能自動在資料更新時更新，來重新載入gridView
    public void showGrid(Context context, boolean showAll){
    	saGrid = new SimpleAdapter(
	    		context,
	    		turnHymnsToListOfMap(showAll),
	    		R.layout.stat_grid_row,
	    		new String[]{"col_index",
	    					 "col_title",
	    					 "col_rating",
	    					 "col_times",
	    					 "col_familiarity"},
	    		new int[]{R.id.grid_index,
	    				  R.id.grid_title,
	    				  R.id.grid_rating,
	    				  R.id.grid_times,
	    				  R.id.grid_familiarity}
        );
        hymnsGrid.setAdapter(saGrid);
    }// end showGrid()
    
    //排序曲目編號
    static class SerialCompare implements Comparator<HashMap<String, Object>>{
    	public int compare(HashMap<String, Object> one, HashMap<String, Object> two){
    		int serial_one = Integer.parseInt( one.get("col_serial").toString() );
    		int serial_two = Integer.parseInt( two.get("col_serial").toString() );
    		return serial_one - serial_two;			//由低到高
    	}
    }
    
    //排序曲目編號
    static class IndexCompare implements Comparator<HashMap<String, Object>>{
    	public int compare(HashMap<String, Object> one, HashMap<String, Object> two){
    		int index_one = Integer.parseInt( one.get("col_index").toString() );
    		int index_two = Integer.parseInt( two.get("col_index").toString() );
    		return index_one - index_two;			//由低到高
    	}
    }
    
    //用來排序評分
    static class RatingCompare implements Comparator<HashMap<String, Object>>{
		public int compare(HashMap<String, Object> one, HashMap<String, Object> two){
			int rating_one = Integer.parseInt( one.get("col_rating").toString() );
			int rating_two = Integer.parseInt( two.get("col_rating").toString() );
			return rating_two - rating_one;			//由高到低
		}
	}
    
    //用來排序唱的次數
    static class TimesCompare implements Comparator<HashMap<String, Object>>{
    	public int compare(HashMap<String, Object> one, HashMap<String, Object> two){
    		int times_one = Integer.parseInt( one.get("col_times").toString() );
    		int times_two = Integer.parseInt( two.get("col_times").toString() );
    		return times_two - times_one;			//由高到低
    	}
    }
    
    //用來排序唱的次數
    static class FamiliarityCompare implements Comparator<HashMap<String, Object>>{
    	public int compare(HashMap<String, Object> one, HashMap<String, Object> two){
    		String familiarity_one = one.get("col_familiarity").toString() ;
    		String familiarity_two = two.get("col_familiarity").toString() ;
    		int value_one = getValue(familiarity_one);
    		int value_two = getValue(familiarity_two);
    			
    		return value_two - value_one;			//由高到低
    	}
    	int getValue(String familiarityString){
    		int value=0;
    		if (familiarityString.equals("極熟") ){value = 5;}
    		else if (familiarityString.equals("極不熟") ){value = 4;}
    		else if (familiarityString.equals("很熟") ){value = 3;}
    		else if (familiarityString.equals("不熟") ) {value = 2;}
    		else if (familiarityString.equals("普通熟") ) {value = 1;}
    		return value;
    	}
    }
}